(function (window, $, undefined) {
  'use strict';

  var dictData = {
    invoiceOrderStatus: {
      '1': '待审核',
      '2': '已审核(未开票)',
      '3': '已开票(未邮寄)',
      '4': '已邮寄',
      '5': '审核未通过'
    },
    billingType: {
      '1': '纸质发票',
      '2': '电子发票'
    },
    title: {}
  };

  var invoiceData = {};

  main(function () {

    var $tableInvoice = $('#table-invoice');
    util.jqGrid($tableInvoice, {
      url: ajaxURL.COUPON + '/billing/select',
      // datatype: 'json',
      autowidth: true,
      height: $(window).height() - 350,
      // multiselect: true,
      // multiboxonly: true,
      //shrinkToFit: false,
      colModel: [
        { name: 'kid', key: true, hidden: true },
        { label: '序号', name: 'kid', width: 50 },
        {
          label: '发票单号', name: 'billingNo', width: 120, formatter: function (v, o, r) {
            return '<a href="javascript:;" class="view" data-id="' + r.kid + '">' + v + '</a>';
          }
        },
        {
          label: '申请时间', name: 'createTime', width: 150, formatter: function (v, o, r) {
            return util.dateFormat(v);
          }
        },
        {
          label: '发票类别', name: 'billingType', width: 100, formatter: function (v, o, r) {
            return dictData.billingType[v] || '';
          }
        },
        {
          label: '发票金额', name: 'money', width: 80, formatter: function (v, o, r) {
            return v / 100 + ' 元';
          }
        },
        {
          label: '发票张数', name: 'billingNumber', width: 80, formatter: function (v, o, r) {
            return v + ' 张';
          }
        },
        {
          label: '金额总数', name: 'amount', width: 80, formatter: function (v, o, r) {
            return v / 100 + ' 元';
          }
        },
        {
          label: '发票抬头', name: 'title', width: 80, formatter: function (v, o, r) {
            return dictData.title[v] || '';
          }
        },
        { label: '公司名称', name: 'company', width: 100 },
        { label: '纳税人识别号', name: 'idNumber', width: 150 },
        { label: '姓名', name: 'userName', width: 80 },
        { label: '电话', name: 'phone', width: 100 },
        {
          label: '地址', name: 'address', width: 200, formatter: function (v, o, r) {
            return r.city + ' ' + v;
          }
        },
        { label: '邮寄单号', name: 'mailNumber', width: 120 },
        {
          label: '发票状态', name: 'orderStatus', width: 100, formatter: function (v, o, r) {
            return dictData.invoiceOrderStatus[v] || '';
          }
        },
        {
          label: '操作', name: '_op', width: 100, formatter: function (v, o, r) {

            var status = +r.orderStatus;

            if (status === 2) {
              return '<a href="javascript:;" class="makeOut" data-id="' + r.kid + '">开票操作</a>';
            } else if (status === 3) {
              return '<a href="javascript:;" class="editMailNumber" data-id="' + r.kid + '">填写快递单号</a>';
            } else if (status === 4) {
              return '<a href="javascript:;" class="editMailNumber" data-id="' + r.kid + '">修改快递单号</a>';
            } else if (status === 5) {
              return '';
            }
            return '<a href="javascript:;" class="verify" data-id="' + r.kid + '">审核操作</a>';

          }
        }
      ],
      pager: '#pager-invoice',
      loadComplete: function (res) {
        invoiceData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            invoiceData[item.kid] = item;
          });
        }
      }
    });

    // 下单时间
    laydate.render({ elem: '#dealDate', range: '至' });

    var $layerInvoice = $('#layer-invoice-view');
    var $layerMail = $('#layer-invoice-mail');
    var $formMail = $('#form-mail');

    util.selectHtml($('[name="orderStatus"]'), dictData.invoiceOrderStatus, '', '', '全部');

    var dictList = [
      'billingType',
      'invoiceCategory'
    ];
    var dictName = [
      'billingType',
      'title'
    ];

    // 处理字典
    util.getDicts(dictList).then(function (datas) {
      $.each(datas, function (_, data) {
        util.selectHtml('select[name="' + dictName[_] + '"]', data, 'value', 'name', '全部');
        $.each(data, function (x, item) {
          dictData[dictName[_]][item.value] = item.name;
        });

        searchTable();
        $('#btn-search').click(searchTable);
      });
    });

    function searchTable() {
      var data = util.formData('#form-search');

      var searchData = {
        orderStatus: data.orderStatus,
        billingType: data.billingType,
        title: data.title,
        orderTimeBegin: '',
        orderTimeEnd: ''
      };

      if (data.rangeTime) {
        var temp = data.rangeTime.split('至');
        searchData.orderTimeBegin = util.getTime($.trim(temp[0]) + ' 00:00:00');
        searchData.orderTimeEnd = util.getTime($.trim(temp[1]) + ' 23:59:59');
      }

      util.searchGrid($tableInvoice, searchData);
    }

    // 查看操作
    $tableInvoice.on('click', '.view', function () {
      var $this = $(this);
      var id = $this.data('id');

      var data = invoiceData[id];

      data.orderTime = util.getDate(data.orderTime);
      util.fillForm($layerInvoice, data);

      util.layerOpen({
        // title: '发票详情',
        title: false,
        content: $layerInvoice,
        area: ['1000px', '']
      });
    });

    // 审核操作
    $tableInvoice.on('click', '.verify', function () {
      var $this = $(this);
      var id = $this.data('id');

      layer.confirm('请确认信息审核是否通过？', {
        title: false,
        btn: ['通过', '不通过', '取消']
      }, function () {
        var url = ajaxURL.COUPON + '/billing/approveBilling?billingId=' + id + '&userId=' + oUser.userId;
        util.post(url, function (res) {
          util.tip.success('操作成功');
          $tableInvoice.trigger('reloadGrid');
        });
      }, function () {
        var url = ajaxURL.COUPON + '/billing/refuse?billingId=' + id + '&userId=' + oUser.userId;
        util.post(url, function (res) {
          util.tip.success('操作成功');
          $tableInvoice.trigger('reloadGrid');
        });
      });
    });

    // 开票操作
    $tableInvoice.on('click', '.makeOut', function () {
      var $this = $(this);
      var id = $this.data('id');

      layer.confirm('请确认是否进行开票？', {
        title: false,
        btn: ['开票', '取消']
      }, function () {
        var url = ajaxURL.COUPON + '/billing/billing?billingId=' + id + '&userId=' + oUser.userId;
        util.post(url, function (res) {
          util.tip.success('操作成功');
          $tableInvoice.trigger('reloadGrid');
        });
      });
    });

    // 表单验证
    var $validateMail = $formMail.validate({
      rules: {
        mailNumber: { required: true, maxlength: 50 }
      },
      messages: {
        mailNumber: { required: '请填写邮寄单号', maxlength: '单号的最大长度为 50' }
      },
      errorPlacement: function (error, element) { // 错误信息位置设置方法
        error.appendTo(element.parents('.form-container')); // 这里的element是录入数据的对象
      }
    });

    // 填写/修改快递单号
    $tableInvoice.on('click', '.editMailNumber', function () {
      var $this = $(this);
      var id = $this.data('id');
      var curData = invoiceData[id];

      util.fillForm($formMail, curData);

      util.layerOpen({
        // title: '发票邮寄单号',
        title: false,
        content: $layerMail,
        area: ['400px', ''],
        btn: ['确认修改', '取消'],
        yes: function (index) {
          var data = util.formData($formMail);

          if ($validateMail.form()) {
            var url = ajaxURL.COUPON + '/billing/send?billingId=' + id + '&userId=' + oUser.userId + '&mailNumber=' + data.mailNumber;
            util.post(url, data, function (res) {
              layer.closeAll();
              util.tip.success('操作成功');
              $tableInvoice.trigger('reloadGrid');
            });
          }
        }
      });
    });

    // 批量审核
    $('#btn-check').click(util.oneCheck($tableInvoice, function (id) {
      layer.confirm('请确认信息审核是否通过？', {
        btn: ['通过', '不通过', '取消']
      }, function () {
        util.tip.warn('审核通过...');
      }, function () {
        util.tip.warn('审核不通过...');
      });
    }));


  });


})(window, jQuery);
